package com.xinchuang.schedule;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinchuang.domain.entity.TestCron;
import com.xinchuang.domain.entity.TestModelMainTable;
import com.xinchuang.domain.type.ModelMainEnum;
import com.xinchuang.entity.api.OaUserParam;
import com.xinchuang.entity.api.UserApi;
import com.xinchuang.mapper.OaUserMapper;
import com.xinchuang.mapper.TestCronMapper;
import com.xinchuang.mapper.TestModelMainTableMapper;
import com.xinchuang.mapper.UserApiMapper;
import com.xinchuang.service.TryOutPlanModService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: 提交试模计划定时
 * @Author: thh
 * @Date: 2024/4/9 15:51
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TryOutPlanSchedule implements ApplicationRunner {

    private final TestCronMapper cronMapper;
    private final UserApiMapper userApiMapper;
    private final OaUserMapper oaUserMapper;
    private final TryOutPlanModService tryOutPlanModService;
    private final TestModelMainTableMapper testModelMainTableMapper;
    private final DefaultSchedulingConfigurer schedulingConfigurer;

    @Value("${cron.submitter}")
    private String submitter;


    /**
     * 开始任务
     *
     * @param taskId         任务名称
     * @param cronExpression cron表达式
     */
    public void startTask(String taskId, String cronExpression) {
        TriggerTask triggerTask = new TriggerTask(() -> changeTryOutPlan(), new CronTrigger(cronExpression));
        schedulingConfigurer.resetTriggerTask(taskId, triggerTask);
    }

    /**
     * 提交试模计划
     */
    private void changeTryOutPlan() {
        log.info("提交试模计划-执行时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        LocalDateTime currentTime = LocalDateTime.now();
        LambdaQueryWrapper<TestModelMainTable> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TestModelMainTable::getYear, getCurrentYear(currentTime));
        wrapper.eq(TestModelMainTable::getWeek, getCurrentWeek(currentTime) + 1);
        wrapper.eq(TestModelMainTable::getStatus, ModelMainEnum.CREATE_PLAN.getCode());
        List<TestModelMainTable> testModelMainTableList = testModelMainTableMapper.selectList(wrapper);
        if (Objects.nonNull(testModelMainTableList) && !testModelMainTableList.isEmpty()) {
            OaUserParam oaUserParam = oaUserMapper.selectOne(new LambdaQueryWrapper<OaUserParam>().eq(OaUserParam::getUsername, submitter));
            //UserApi userApi = userApiMapper.selectOne(new LambdaQueryWrapper<UserApi>().eq(UserApi::getUsername, submitter));
            if (Objects.nonNull(oaUserParam)) {
                testModelMainTableList.forEach(testModelMainTable -> {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("planId", testModelMainTable.getId());
                    tryOutPlanModService.changeTryOutPlan(jsonObject, null, oaUserParam.getId());
                });
            }
        }
    }

    /**
     * 项目启动时加载已存在的定时
     *
     * @param args
     */
    @Override
    public void run(ApplicationArguments args) {
        List<TestCron> cronList = cronMapper.selectList(new LambdaQueryWrapper<TestCron>().orderByAsc(TestCron::getCreateTime));
        if (Objects.nonNull(cronList) && !cronList.isEmpty()) {
            TestCron testCron = cronList.get(0);
            TriggerTask triggerTask = new TriggerTask(() -> changeTryOutPlan(), new CronTrigger(testCron.getCronExpression()));
            schedulingConfigurer.resetTriggerTask(testCron.getId(), triggerTask);
        }
    }

    /**
     * 获取当前时间的年份
     *
     * @param currentTime
     * @return
     */
    public static int getCurrentYear(LocalDateTime currentTime) {
        return currentTime.getYear();
    }

    /**
     * 获取当前时间的周数
     *
     * @param currentTime
     * @return
     */
    public static int getCurrentWeek(LocalDateTime currentTime) {
        return currentTime.get(WeekFields.ISO.weekOfYear());
    }

    public static void main(String[] args) {
        System.out.println(getCurrentWeek(LocalDateTime.now()));
    }

}
